/**
 *
 */
package com.wedroid.api.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.demo2do.core.persistence.GenericDaoSupport;
import com.demo2do.core.support.Page;
import com.wedroid.api.service.MessageService;
import com.wedroid.entity.contact.Contacter;
import com.wedroid.entity.message.Message;

/**
 * @author lute
 */
@Service("messageService")
public class MessageServiceImpl implements MessageService {

    @Autowired
    private GenericDaoSupport genericDaoSupport;

    /* (non-Javadoc)
     * @see com.wedroid.webapp.service.MessageService#countMessages(com.wedroid.entity.contact.Contacter)
     */
    public int countMessages(Contacter contacter) {
        String sentence = "SELECT COUNT(*) FROM Message message WHERE message.sender = :contacter OR message.receiver = :contacter";
        Map<String, Object> parameters = new HashMap<>();
        parameters.put("contacter", contacter);
        return genericDaoSupport.count(sentence, parameters);
    }

    /* (non-Javadoc)
     * @see com.wedroid.api.service.MessageService#listMessages(com.wedroid.entity.contact.Contacter, com.demo2do.core.support.Page)
     */
    @SuppressWarnings("unchecked")
    public List<Message> listMessages(Contacter contacter, Page page) {

        String sentence = "FROM Message message WHERE message.sender = :contacter OR message.receiver = :contacter ORDER BY message.messageTime DESC";
        List<Message> result = genericDaoSupport.searchForList(sentence, "contacter", contacter, page.getBeginIndex(), page.getMaxResultRecords());

        page.calculate(result.size());
        return result.size() > page.getEveryPage() ? result.subList(0, page.getEveryPage()) : result;
    }

}
